var GAMESTATES = {PLACINGPHASE: 0, PLAYER1MOVE: 1, PLAYER2MOVE: 2, PLAYER1WIN: 3, PLAYER2WIN: 4};
var activeTileIntervalID = null;
var currentActiveTile = null;

var latitude = null;
var longitude = null;
var flagLat = null;
var flagLng = null;
var sensitivity = 0.00005;
var flagSet = false;

var playersEstablished = false;
var players = {};
var user = 0;
var requesterID;

function latLngToTileCoord(lat, lng) {

    if (flagLat !== null && flagLng !== null) {

        var coordString;
        var latCoord = Math.floor((lat - flagLat) / sensitivity);
        var lngCoord = Math.floor((lng - flagLng) / sensitivity);

        if (latCoord < 0) {

            coordString = 'J';

        } else if (latCoord > 9) {

            coordString = 'A';

        } else {

            coordString = String.fromCharCode(74 - latCoord);
        }

        if (lngCoord < 0) {

            coordString += '0';

        } else if (lngCoord > 9) {

            coordString += '9';

        } else {

            coordString += latCoord;
        }

        return coordString;

    } else {

        return "Error: Flag not set";

    }
}

function SetFlag() {

    flagLat = latitude;
    flagLng = longitude;

    setActiveTile(latLngToTileCoord(flagLat, flagLng));

    flagSet = true;
}

function GPSLocationHandler(position) {

    $("#latLabel").html(position.coords.latitude).css('color', 'lawngreen').css('font-size', '5rem');
    $("#lngLabel").html(position.coords.longitude).css('color', 'lawngreen').css('font-size', '5rem');

    latitude = position.coords.latitude;
    longitude = position.coords.longitude;

    if (flagSet) {

        var currentTile = latLngToTileCoord(latitude, longitude);

        if (currentTile != currentActiveTile.attr('name')) {

            setActiveTile(currentTile);
        }
    }
}

function errorHandler(err) {

    $("#message").html("<div id='serverErrorMessage'><p>" + err + "</p></div>");

}

function updateGPSLocation() {

    navigator.geolocation.getCurrentPosition(GPSLocationHandler, errorHandler);

}

function setActiveTile(pos) {

    if (activeTileIntervalID != null) {

        clearInterval(activeTileIntervalID);

        currentActiveTile.css('border-color', 'lawngreen').css('border-width', '.1rem');

    }

    currentActiveTile = $("[name=" + pos + "]").css('color', 'red').css('text-align', 'center').css('font-size', '6rem');

    activeTileIntervalID = setInterval(function () {

        if (currentActiveTile.css('border-color') == 'rgb(255, 255, 255)') {

            currentActiveTile.css('border-color', 'lawngreen').css('border-width', '.1rem');

        } else {

            currentActiveTile.css('border-color', 'white').css('border-width', '.2rem');
        }

    }, 800);
}

/*
 function testSAT(){
 setActiveTile('A1');
 setTimeout(function(){
 setActiveTile('D6');
 }, 5000)
 }
 */

function takeShot() {

    var shot = {coord: currentActiveTile.attr("name")};

    $.ajax({

        type: "POST",
        url: "/request",
        data: JSON.stringify(shot),
        contentType: "application/json",
        cache: false,
        timeout: 5000,

        success: function (data) {

            if (typeof data.error == 'undefined') {

                if (data.status != "success") {
                    $("#message").html("<div id='serverWarningMessage'><p>" + data.status + "</p></div>");

                }

                requestGameState();

            } else {

                $("#message").html("<div id='serverErrorMessage'><p>" + 'Error: ' + data.error + "</p></div>");

            }

        }, error: function (jqXHR, textStatus, errorThrown) {

            $("#message").html("<div id='serverErrorMessage'><p>" + 'error ' + textStatus + " " + errorThrown + "</p></div>");

        }
    });
}

function placeShip() {

    var ship = {'type': $("#shipSelect").find("option:selected").html(), 'pivotPoint': currentActiveTile.attr("name"),
        'orientation': $("#orientationSelect").find("option:selected").html()};

    var shipRequest = JSON.stringify(ship);

    console.log(shipRequest);

    $.ajax({
        type: "POST",
        url: "/request",
        data: shipRequest,
        contentType: "application/json",
        cache: false,
        timeout: 5000,

        success: function (data) {

            if (typeof data.error == 'undefined') {

                if (data.status != "success") {

                    $("#message").html("<div id='serverWarningMessage'><p>" + data.status + "</p></div>");
                }
                requestGameState();
            } else {
                $("#message").html("<div id='serverErrorMessage'><p>" + 'Error: ' + data.error + "</p></div>");

            }

        }, error: function (jqXHR, textStatus, errorThrown) {

            $("#message").html("<div id='serverErrorMessage'><p>" + 'error ' + textStatus + " " + errorThrown + "</p></div>");

        }
    });
}

function requestGameState() {

    $.ajax({
        type: "POST",
        url: "/requestGameState",
        cache: false,
        timeout: 5000,
        success: function (data) {

            if (typeof data.error == 'undefined') {

                var response = JSON.parse(data.response);

                console.log("Response is: " + response);

                var i = 0;

                for (var player in response) {

                    i++;
                    if (!playersEstablished) {
                        players[i] = player;
                    }

                    console.log("the player is: " + response[player]);
                    updateShips("#gameboard-p" + i, response[player].ships);

                }

                for (var player in response) {

                    updateShots("#gameboard-p" + i, response[player].hits, response[player].misses);
                    i--;

                }

                if (!playersEstablished) {

                    user = 1;
                    if ($("#switchView").val() == players[2]) {

                        $("#gameboard-p2").css("display", "block");
                        $("#gameboard-p1").css("display", "none");
                        user = 2;

                    }

                    playersEstablished = true;

                }

                var state = JSON.parse(data.state);

                console.log(state);

                if (state == GAMESTATES.PLACINGPHASE) {

                    if ($("#placeShipButton").attr("disabled") !== undefined) {

                        $("#placeShipButton").removeAttr("disabled");

                    }

                    $("#bombButton").attr('disabled', 'disabled');

                } else if ((state == GAMESTATES.PLAYER1MOVE && user == 1) || (state == GAMESTATES.PLAYER2MOVE && user == 2)) {

                    if ($("#bombButton").attr("disabled") !== undefined) {

                        $("#bombButton").removeAttr("disabled");

                    }

                    $("#placeShipButton").attr('disabled', 'disabled');

                } else if ((state == GAMESTATES.PLAYER1WIN && user == 1) || (state == GAMESTATES.PLAYER2WIN && user == 2)) {

                    $("#placeShipButton").attr('disabled', 'disabled');
                    $("#bombButton").attr('disabled', 'disabled');

                    alert("Congratulations, You Win!");

                } else if (state == GAMESTATES.PLAYER1WIN || state == GAMESTATES.PLAYER2WIN) {

                    $("#placeShipButton").attr('disabled', 'disabled');
                    $("#bombButton").attr('disabled', 'disabled');

                    alert("Congratulations, You Lose!");
                    clearInterval(requesterID);

                }

            } else {

                $("#message").html("<div id='serverWarningMessage'><p>" + data.error + "</p></div>");
                clearMessage(3000);

            }

        }, error: function (jqXHR, textStatus, errorThrown) {

            $("#message").html("<div id='serverErrorMessage'><p>" + 'Error ' + textStatus + " " + errorThrown + "</p></div>");
            clearMessage(3000);

        }
    });
}

function clearMessage(delay) {

    setTimeout(function () {

        $("#message").html("");

    }, delay);
}

$(document).ready(function () {

    for (var ship in BATTLESHIPS) {

        $("option[value='" + ship + "']").css("background-color", BATTLESHIPS[ship]);

    }

    updateGPSLocation();
    setInterval(updateGPSLocation, 2000);

    requestGameState();
    requesterID = setInterval(requestGameState, 5000);

    $("#flagButton").click(function () {

        SetFlag();

    });

    $("#switchView").click(function () {

        if ($("#gameboard-p1").css("display") == "none") {

            $("#switchView").val(players[1]);
            $("#gameboard-p1").css("display", "block");
            $("#gameboard-p2").css("display", "none");

        } else {

            $("#switchView").val(players[2]);
            $("#gameboard-p2").css("display", "block");
            $("#gameboard-p1").css("display", "none");

        }
    });

    $("#bombButton").click(function () {

        takeShot();

    });

    $("#placeShipButton").click(function () {

        placeShip();

    });

    $("#sensitivity").click(function () {

        sensitivity = $("[name=sensitivity]").val();
        
    });
});
